package com.metaverse.backend.utils;

import com.metaverse.backend.exception.BusinessException;
import net.coobird.thumbnailator.Thumbnails;
import org.pngquant.PngQuant;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {

    public static BufferedImage resizeJpg(InputStream image, int width, int height, boolean compress) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(image);
        if(bufferedImage == null){
            throw new BusinessException("图片读取失败，请确认是否是标准格式");
        }
        return resizeJpg(bufferedImage, width, height, compress);
    }

    public static BufferedImage resizeJpg(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
        return Thumbnails.of(bufferedImage)
                .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
                .outputFormat("jpg")
                .outputQuality(compress ? 0.7 : 1.0)
                .asBufferedImage();
    }

    public static BufferedImage resizePng(InputStream image, int width, int height, boolean compress) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(image);
        if(bufferedImage == null){
            throw new BusinessException("图片读取失败，请确认是否是标准格式");
        }
        return resizePng(bufferedImage, width, height, compress);
    }

    public static BufferedImage resizePng(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
        if (compress) {
            BufferedImage img = Thumbnails.of(bufferedImage)
                    .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
                    .outputFormat("png")
                    .outputQuality(1.0)
                    .asBufferedImage();
            PngQuant pngQuant = new PngQuant();
            return pngQuant.getRemapped(img);
        } else {
            return Thumbnails.of(bufferedImage)
                    .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
                    .outputFormat("png")
                    .outputQuality(1.0)
                    .asBufferedImage();
        }
    }

    public static void main(String[] args) throws IOException {
//        ImageUtils.resizePng(new FileInputStream("C:\\Users\\xyhy\\Desktop/微信图片_20220331105255.png"), 1000, 2000, true);
        PngQuant pngQuant = new PngQuant();
//        ImageIO.write(pngQuant
//                        .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.png"))),
//                "png", new File("/Users/drew/Desktop/2.png"));
    }
}
